package cn.wonderland.service.impl;

import cn.wonderland.domain.Order;
import cn.wonderland.domain.Product;
import cn.wonderland.domain.User;
import cn.wonderland.dto.OrderListDto;
import cn.wonderland.feign.client.UserFeignClient;
import cn.wonderland.mapper.OrderMapper;
import cn.wonderland.service.OrderService;
import cn.wonderland.utils.JSONResult;
import cn.wonderland.vo.orderlist.OrderListVo;
import cn.wonderland.vo.orderlist.OrderVo;
import cn.wonderland.vo.orderlist.TypeOrderListVo;
import cn.wonderland.vo.report.ReportVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserFeignClient userFeignClient;


    /**
     * 查询指定月份的订单
     *
     * @param dto
     */
    @Override
    public JSONResult<List<TypeOrderListVo>> getOrderList(@RequestBody OrderListDto dto) {
        List<Order> orderList;
        if(dto.getYear() == null) { // 如果年份为空，则默认查询当前年份的订单
            LocalDate currentDate = LocalDate.now();
            int currentYear = currentDate.getYear();
            orderList = orderMapper.findOrderList(currentYear, dto.getMonth());
        } else { // 如果指定了年份，则按指定年份和月份进行查询
            orderList = orderMapper.findOrderList(dto.getYear(), dto.getMonth());
        }

        List<OrderVo> orderVolist = new ArrayList<>();
        Map<String, List<OrderVo>> resultMap = new HashMap<>();

        for (Order order : orderList) {
            OrderVo orderVo = new OrderVo();

            Long categoryId = order.getCategoryId();
            Long userId = order.getUserId();
            Long productId = order.getProductId();

            orderVo.setOrderDate(order.getOrderDate());

            Product product = orderMapper.findTypeByCategoryId(categoryId);
            orderVo.setProductName(orderMapper.findProductById(productId).getName()); // 直接设置商品名

            orderVo.setPrice(orderMapper.findProductById(productId).getPrice()); // 直接设置商品价格

            JSONResult<User> userByUserId = userFeignClient.getUserByUserId(userId);
            int code = userByUserId.getCode();
            if (code != 100052) {
                User user = userByUserId.getData();
                orderVo.setUserName(user.getName());
                orderVo.setPhone(user.getPhone());
            } else {
                return JSONResult.<List<TypeOrderListVo>>builder()
                        .message("用户服务熔断！")
                        .code(100052)
                        .success(false)
                        .data(null)
                        .build();
            }

            orderVolist.add(orderVo);

            String type = product.getName();
            // 如果结果集中已存在当前分类，将 OrderVo 对象加入到分类对应的集合中
            if (resultMap.containsKey(type)) {
                resultMap.get(type).add(orderVo);
                // 如果结果集中不存在当前分类，创建新集合并将 OrderVo 对象加入其中
            } else {
                List<OrderVo> newOrderVoList = new ArrayList<>();
                newOrderVoList.add(orderVo);
                resultMap.put(type, newOrderVoList);
            }
        }
        List<TypeOrderListVo> typeOrderListVos = new ArrayList<>();
        for (Map.Entry<String, List<OrderVo>> entry : resultMap.entrySet()) {
            TypeOrderListVo typeOrderListVo = new TypeOrderListVo();
            typeOrderListVo.setType(entry.getKey());
            typeOrderListVo.setOrderList(entry.getValue());
            typeOrderListVos.add(typeOrderListVo);
        }

        JSONResult<List<TypeOrderListVo>> result = JSONResult.<List<TypeOrderListVo>>builder()
                .message("请求成功")
                .code(200)
                .success(true)
                .data(typeOrderListVos)
                .build();
        return result;
    }


    /**
     * 查询订单报表
     * @param dto
     */
    @Override
    public List<ReportVo> report(OrderListDto dto) {
        List<Order> orderList;
        if(dto.getMonth() == null) { // 如果月份为空，则默认查询当前月份的订单
            LocalDate currentDate = LocalDate.now();
            int monthValue = currentDate.getMonthValue();
            orderList = orderMapper.findOrderList(dto.getYear(), monthValue);
        } else { // 如果指定了月份，则按指定年份和月份进行查询
            orderList = orderMapper.findOrderList(dto.getYear(), dto.getMonth());
        }

        Map<Long, ReportVo> reportMap = new HashMap<>();
        for (Order order : orderList) {
            Long categoryId = order.getCategoryId();
            Product type = orderMapper.findTypeByCategoryId(categoryId);
            Long productId = order.getProductId();
            Product product = orderMapper.findProductById(productId);
            BigDecimal price = product.getPrice();

            int quantity = 1;
            if (reportMap.containsKey(categoryId)) {
                ReportVo reportVo = reportMap.get(categoryId);
                reportVo.setTotalNum(reportVo.getTotalNum() + quantity);
                reportVo.setTotalPrice(reportVo.getTotalPrice().add(price.multiply(BigDecimal.valueOf(quantity))));
            } else {
                ReportVo reportVo = new ReportVo();
                reportVo.setType(type.getName());
                reportVo.setTotalNum(quantity);
                reportVo.setTotalPrice(price.multiply(BigDecimal.valueOf(quantity)));
                reportMap.put(categoryId, reportVo);
            }
        }
        List<ReportVo> reportVolist = new ArrayList<>(reportMap.values());
        return reportVolist;
    }

}
